package hotel.meituan.oversea.biz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.utils.HttpClientBaseAuth;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.StringUtil;
import hotel.meituan.oversea.api.entity.MtHotelOrderCheckHistory;
import hotel.meituan.oversea.biz.mapper.MtHotelOrderCheckHistoryMapper;
import hotel.meituan.oversea.biz.service.MtHotelOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.util.*;
import java.util.concurrent.*;

/**
 * 美团酒店信息Controller
 * @author qiuyy
 * @date 2020-05-15
 */
@Slf4j
@RestController
@RequestMapping("/mtTest")
@Api(value = "MtTestController", tags = {"美团酒店接口"})
public class MtTestController {

    @Autowired
    MtHotelOrderService mtHotelOrderService;
    @Autowired
    MtHotelOrderCheckHistoryMapper mtHotelOrderCheckHistoryMapper;

    @Autowired
    RestTemplate restTemplate;

    @PostMapping("/getMtTest")
    @ApiOperation(value = "获取酒店id",notes="必须经过auth授权")
    public Result<Object> getMtTest(@RequestBody JSONObject jsonObject){
        log.info("jsonObject: {}",jsonObject);
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = null;
        try {
            objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        }
        String port = objectNames.iterator().next().getKeyProperty("port");

        log.info("当前调用端口为{}的美团服务",port);


        log.info("---> 开始调用:携程服务；");
        String accessToken = HttpClientBaseAuth.getAuthToken();
        String host = CommonUrlConstants.SWITCHS_HOST;
        String updateUrl = host + "/switchTest/getSwitchsTestFinal";// +"?access_token="+accessToken

        Map params = new HashMap();
        params.put("retMsg"," 调用 携程结束测试接口通知 ");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
        HttpEntity<String> strEntity = new HttpEntity<String>(JSON.toJSONString(params),headers);
        //发起请求
        Result response = null;
        try{
            response = restTemplate.postForObject(updateUrl,strEntity,Result.class);
        }catch (Exception e){
            log.error(" 携程通知 请求内部处理接口  发起请求 异常 catch: {},{},{}",
                    updateUrl, JSON.toJSONString(params), JSON.toJSONString(response));
            log.error(e.getMessage(),e);
        }

        return new Result<>(CommonConstants.SUCCESS);
    }

    /**
     * 测试美团批量新增
     * @return
     */
    @PostMapping("/getMtOrderTest")
    public Result<Object> getMtOrderTest(){
        hotelMapFetch();
        return new Result<>();
    }


    public void insertList(){
        List<MtHotelOrderCheckHistory> mtHotelOrderCheckHistories = new ArrayList<>();
        List<String> hotelIdList = new ArrayList<>();
        for(int i=0;i<10000;i++){
            MtHotelOrderCheckHistory mtHotelOrderCheckHistory = new MtHotelOrderCheckHistory();
            mtHotelOrderCheckHistory.setId(StringUtil.getUUID());
            mtHotelOrderCheckHistory.setMtHotelId("2147275"+String.valueOf(i));
            mtHotelOrderCheckHistory.setMtGoodsId("17552058");
            mtHotelOrderCheckHistory.setMtCheckinDate("2020-07-27 00:00:00");
            mtHotelOrderCheckHistory.setMtCheckoutDate("2020-07-28 00:00:00");
            mtHotelOrderCheckHistory.setMtRoomNum(1);
            mtHotelOrderCheckHistory.setMtTotalPrice(192);
            mtHotelOrderCheckHistory.setMtRemainRoomNum(888);
            mtHotelOrderCheckHistory.setState(0);
            mtHotelOrderCheckHistory.setRemark("");
            mtHotelOrderCheckHistory.setCreateTime(new Date());
            mtHotelOrderCheckHistory.setModifyTime(new Date());

            hotelIdList.add("2147275");

            mtHotelOrderCheckHistories.add(mtHotelOrderCheckHistory);
        }

        Example example = new Example(MtHotelOrderCheckHistory.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("mtHotelId",hotelIdList);

        int delInt = mtHotelOrderCheckHistoryMapper.deleteByExample(example);
        log.info("delInt : {}",delInt);
        if(delInt != -1){
            int istInt = mtHotelOrderCheckHistoryMapper.insertList(mtHotelOrderCheckHistories);
            log.info("istInt : {}",istInt);
        }
    }



    public void hotelMapFetch() {

        System.out.println("----程序开始运行----");
        Date date1 = new Date();

        //创建10个线程
        int taskSize = 10;
        // 创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);
        // 创建多个有返回值的任务
        List<Future> list = new ArrayList<Future>();
        for (int i = 0; i < taskSize; i++) {
            Callable c = new HotelCompareCallable(i + "");
            // 执行任务并获取 Future 对象
            Future f = pool.submit(c);
            // System.out.println(">>>" + f.get().toString());
            list.add(f);
        }
        // 关闭线程池
        pool.shutdown();

        // 获取所有并发任务的运行结果
        for (Future f : list) {
            // 从 Future 对象上获取任务的返回值，并输出到控制台
            try {
                System.out.println(">>>" + f.get().toString());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        Date date2 = new Date();
        System.out.println("----程序结束运行----，程序运行时间【"
                + (date2.getTime() - date1.getTime()) + "毫秒】");
    }

    /**
     * 返回值线程
     */
    class HotelCompareCallable implements Callable<Object> {
        private String taskNum;

        HotelCompareCallable(String taskNum) {
            this.taskNum = taskNum;
        }

        @Override
        public Object call() throws Exception {
            System.out.println(">>>" + taskNum + "任务启动");
            taskNum = taskNum.trim();
            Date dateTmp1 = new Date();
            Thread.sleep(100);
            //根据创建线程调用对应hotelCompareMap 进行校验
            if (Integer.valueOf(taskNum) == 0) {
                insertList();
            } else if (Integer.valueOf(taskNum) == 1) {
                insertList();
            } else if (Integer.valueOf(taskNum) == 2) {
                insertList();
            } else if (Integer.valueOf(taskNum) == 3) {
                insertList();
            } else if (Integer.valueOf(taskNum) == 4) {
                insertList();
            } else if (Integer.valueOf(taskNum) == 5) {
                insertList();
            } else if (Integer.valueOf(taskNum) == 6) {
                insertList();
            } else if (Integer.valueOf(taskNum) == 7) {
                insertList();
            } else if (Integer.valueOf(taskNum) == 8) {
                insertList();
            } else if (Integer.valueOf(taskNum) == 9) {
                insertList();
            }


            Date dateTmp2 = new Date();
            long time = dateTmp2.getTime() - dateTmp1.getTime();
            System.out.println(">>>" + taskNum + "任务终止");
            return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";
        }
    }

}
